import { getItem, setItem } from '@/utils/auth.js'
import { userProfile } from '@/api/user.js'

// vuex存储数据的对象, 用于不同组件间通信
const state = {
  // token数据
  token: getItem() || '',
  userInfo: '',
  refresh_token: localStorage.getItem('refresh_token') || ''
}

// vuex设置/修改数据的对象
const mutations = {
  // 提供一个设置 state对象里 token属性的方法
  setToken (state, value) {
    state.token = value
    setItem(value)
  },
  setUserInfo (state, value) {
    state.userInfo = value
  },
  // 修改userInfo中某个属性
  setUserOther (state, value) {
    state.userInfo[value.key] = value.value
  },
  // 修改refresh_token
  setRefreshToken (state, value) {
    state.refresh_token = value
    localStorage.setItem('refresh_token', value)
  }
}

const actions = {
  async getUserInfo (store) {
    if (store.state.userInfo === '') {
      const res = await userProfile()
      store.commit('setUserInfo', res.data)
    }
  }
}
const getters = {
  getToken (state) {
    return state.token
  }
}

// 导出 user.js 模块的vuex对象
export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}
